<template>
  <PageWrapper>
    <div class="select-channel">
      <div class="channel-name">渠道名称</div>
      <div class="channel-select">
        <AllSelect
          v-model:selectValue="stateData.channelCode"
          :key="stateData.selectKey"
          :maxTagCount="6"
          :disabledSelect="stateData.channelList.length === 1"
          :options="channelTreeData"
        />
      </div>
      <div class="channel-icon" @click="searchData">
        <search-outlined />
      </div>
    </div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <div class="table-total">
          <div class="total-num">
            共
            <span>{{ stateData.totalNum.orgCount || 0 }}</span>
            个企业
          </div>
          <div class="total-num">
            订单总数
            <span>{{ stateData.totalNum.sumCount || 0 }}</span>
            条
          </div>
          <div class="total-num">
            开票成功
            <span>{{ stateData.totalNum.sucCount || 0 }}</span>
            张
          </div>
          <div class="total-num">
            开票中
            <span>{{ stateData.totalNum.ingCount || 0 }}</span>
            张
          </div>
          <div class="total-num">
            开票失败
            <span>{{ stateData.totalNum.failCount || 0 }}</span>
            张
          </div>
          <div class="total-num">
            开票金额
            <span>{{ formatMoney(stateData.totalNum.sumAmt) || '0.00' }}</span>
            元
          </div>
        </div>
        <div class="export-btn">
          <a-space :size="12">
            <a-button
              type="primary"
              v-auth="permissionCodeMap.statisticExport"
              @click="statisticExport"
              :loading="exportLoading"
              >导出</a-button
            >
          </a-space>
        </div>
      </template>
      <template #bodyCell="{ column, record, text }">
        <template v-if="column.dataIndex === 'sucRate'">
          <span>{{ record.sucRate }}%</span>
        </template>
        <template v-else-if="column.dataIndex === 'sumAmt'">
          <span>{{ formatMoney(record.sumAmt) }}</span>
        </template>
      </template>
    </BasicTable>
  </PageWrapper>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, watch, createVNode, onMounted } from 'vue'
import PageWrapper from '@/components/PageWrapper/index.vue'
import { BasicTable, useTable } from '@/components/Table'
import { getOrderBasicColumns, getSearchFormConfig } from './dataSource'
import { message, Modal } from 'ant-design-vue'
import { constantMap } from '@/types/enum'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'
import AllSelect from '@/components/AllSelect/index.vue'
import { permissionCodeMap } from '@/utils/permissionCodeMap'
import { ALL_SELECT } from '@/utils/constantMap'
import { timeDiff } from '@/utils/dateUtil'
import { formatMoney } from '@/utils/index'
import { cloneDeep } from 'lodash-es'
import { SearchOutlined } from '@ant-design/icons-vue'
import { createChannelTree, transformToTree } from '@/utils'
import api from '@/api'
import { downExcel } from '@/utils/axios/request'
import dayjs from 'dayjs'
const { analysisQueryPage, analysisQueryTotal, queryChannelList, anslysisExport } = api

const stateData = reactive<any>({
  selectKey: 0,
  channelList: [],
  channelCode: [],
  reqData: {},
  totalNum: {}
})
const channelTreeData = ref<any>([])
const exportLoading = ref(false)
const [registerTable, { reload, setPagination, getForm }] = useTable({
  api: analysisQueryPage,
  columns: getOrderBasicColumns(),
  useSearchForm: true,
  formConfig: getSearchFormConfig(),
  showIndexColumn: true,
  indexColumnProps: {
    fixed: 'left'
  },
  immediate: false,
  sortFn: (sorter) => {
    const { field, order } = sorter
    if (!order) {
      return null
    }
    const asc = order === 'ascend' ? true : false
    const fieldMap: any = {
      sumCount: 'sum_count',
      sucCount: 'suc_count',
      ingCount: 'ing_count',
      failCount: 'fail_count',
      sumAmt: 'sum_amt'
    }
    let orders = [{ asc, column: fieldMap[field] }]
    return { orders }
  },
  beforeFetch: (data) => {
    if (!(data.beginDate && data.endDate)) {
      message.error('请选择时间区间')
      throw Error('请选择时间区间')
      return
    } else if (Math.abs(timeDiff(data.beginDate, data.endDate, 'day')) > 365) {
      message.error('您选择的时间区间超过了365天，请重新选择')
      throw Error('您选择的时间区间超过了365天，请重新选择')
      return
    }

    let channelCodeSet = stateData.channelCode.filter((item: string) => item !== ALL_SELECT)
    data.channelCodeSet = channelCodeSet

    if (data.page && data.orders) {
      data.page.orders = data.orders
      delete data.orders
    }

    let reqData = cloneDeep(data)
    if (reqData.page) {
      delete reqData.page
    }
    stateData.reqData = reqData
    getTotalNum()

    return data
  },
  scroll: { x: constantMap.tableXWidth }
})

const searchData = () => {
  reload()
}
// 获取总数
const getTotalNum = async () => {
  let res = await analysisQueryTotal(stateData.reqData)
  stateData.totalNum = res.result || {}
}
// 获取渠道列表
const getQueryChannelList = async () => {
  let res = await queryChannelList()
  let result = res.result || []
  let channelCode: any[] = []
  channelTreeData.value = transformToTree(result)

  console.log('测试数据======>', channelTreeData.value)
  if (result && result.length) {
    result.forEach((item: any) => {
      channelCode.push(item.channelCode)
    })
  }
  stateData.channelCode = channelCode
  stateData.channelList = result
  if (stateData.channelList.length > 1) {
    channelTreeData.value.unshift({
      parentChannelCode: null,
      channelCode: 'ALL_SELECT',
      channelName: '全选'
    })
  }
  console.log('channelList===>', stateData.channelList)
  stateData.selectKey++
  reload()
}
onMounted(() => {
  getQueryChannelList()
})
const statisticExport = async () => {
  const { getFieldsValue } = getForm()
  const formData = getFieldsValue()
  let channelCodeSet = stateData.channelCode.filter((item: string) => item !== ALL_SELECT)
  const reqParams = { ...formData, channelCodeSet }
  const { beginDate, endDate } = formData
  if (!(beginDate && endDate)) {
    message.error('请选择时间区间')
    throw Error('请选择时间区间')
  } else if (Math.abs(timeDiff(beginDate, endDate, 'day')) > 365) {
    message.error('您选择的时间区间超过了365天，请重新选择')
    throw Error('您选择的时间区间超过了365天，请重新选择')
  }
  exportLoading.value = true
  let nowTime = dayjs().format('YYYYMMDDHHmmss')
  try {
    let res = await downExcel('/api/tenant/manager/statistic/analysis/export', reqParams, `统计分析_${nowTime}`)
    exportLoading.value = false
    message.success('导出成功')
  } catch (error) {
    exportLoading.value = false
  }
}
</script>

<style lang="less" scoped>
.select-channel {
  display: flex;
  align-items: center;
  padding: 0 0 16px 28px;
  margin-bottom: 16px;
  border-bottom: 1px solid #e0e1e6;
  .channel-name {
    font-size: 12px;
    margin-right: 4px;
    flex-shrink: 0;
  }
  .channel-select {
    min-width: 320px;
  }

  .channel-icon {
    width: 32px;
    height: 32px;
    flex-shrink: 0;
    color: #555d6f;
    font-size: 12px;
    border: 1px solid #cdcdcd;
    margin-left: -1px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    &:hover {
      color: @primary-color;
      border-color: @primary-color;
      z-index: 2;
    }
  }
}
.table-total {
  width: 100%;
  height: 48px;
  line-height: 48px;
  background: #fafafa;
  border-radius: 4px;
  padding-left: 14px;
  color: #192235;
  font-size: 14px;
  display: flex;
  align-items: center;
  .total-num {
    margin-right: 16px;
    span {
      font-weight: 600;
      color: @primary-color;
      padding: 0 4px;
    }
  }
}
:deep(.basic-table-header) {
  padding: 0;
  flex-direction: column;
}
.export-btn {
  display: flex;
  justify-content: left;
  width: 100%;
  margin-top: 8px;
}
</style>
